package be.xios.projectquiz.engine;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import be.xios.projectquiz.statuspanels.UpdatePanels;

/// <summary>
/// Deze klasse opent de socket van de server en instantieert serverthreads bij elke inkomende aanvraag
/// </summary>
/// <author>Sebastian Kubski</author>
public class Server implements Runnable {

	private ServerThread sthread;
	private UpdatePanels updatepanels;
	private GameSettings settings;
	private ServerSocket sSocket;
	
	public Server(UpdatePanels updatepanels) { 
		this.settings = new GameSettings();
		this.updatepanels=updatepanels;
    }
     
	@Override
	public void run() {
    	
		try {
			sSocket = new ServerSocket(5000, 100);
			
			updatepanels.updateGameLogPanel("Server started at: " + new Date() + "\n" + "Server running on port: 5000 with queuelength: 100");
            
           ExecutorService executor = Executors.newCachedThreadPool();
           
           while(true) {
                Socket socket = sSocket.accept();
                //Nieuwe thread openen voor iemand die connect           
                sthread = new ServerThread(socket, settings, updatepanels);
                //Uitvoeren
                executor.execute( sthread );                      
            }
        } 
		catch(IOException exception) {
            System.out.println("\nError: " + exception);
        }
	}
	
}

